package com.smart.stock.common.util.h2;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/** * 简易版连接池
 * spring.datasource.driver-class-name=org.h2.Driver
 * spring.datasource.url=jdbc:h2:mem:andrew
 * spring.datasource.username=root
 * spring.datasource.password=root
 * */
@Component
public class H2ConnectionPool {
	//静态Connection队列
	private static LinkedList<Connection> connections;
	//加载驱动
	static{
		try{
			Class.forName("org.h2.Driver");
			getConnection();
			}catch(ClassNotFoundException e){
				e.printStackTrace();
			}
		}

	/** * 获取连接，多线程访问并发控制 */
	public synchronized static Connection getConnection(){
		try{
			if(connections ==null){
				connections =new LinkedList<Connection>();
				for(int i =0;i<15;i++){
					Connection conn = DriverManager.getConnection("jdbc:h2:mem:andrew", "root", "root" );
					connections.push(conn);
				}
				System.out.println("h2初始化成功，连接数为："+connections.size());

			}
		}catch(Exception e){
			e.printStackTrace();
		}

		Connection conn = connections.poll();
		System.out.println("获取h2连接成功，剩余连接数为："+connections.size());
		return conn;
	}

	public static void returnConnection(Connection conn){
		connections.push(conn);
		System.out.println("归还h2连接成功，剩余连接数为："+connections.size());
	}

	public static void closeConnections(){
		if (connections == null) {
			return;
		}

		for (int i = 0; i < connections.size(); i++) {
			Connection conn = connections.get(i);
			if (conn!=null){
				try {
					//System.out.println(conn.toString());
					conn.close();
					conn=null;
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}


}
